var Fontmin = require('fontmin');
var through = require('through2');
var isTtf = require('is-ttf');
var _ = require('lodash');
var b2a = require('b3b').b2a;
var replaceExt = require('replace-ext');



//转base64
const ttf2base64 = function(opts){
    opts = _.extend({clone: true}, opts);
        
    return through.ctor({
        objectMode: true
    }, function(file, enc, cb){
         // check null
        if (file.isNull()) {
            cb(null, file);
            return;
        }

        // check stream
        if (file.isStream()) {
            cb(new Error('Streaming is not supported'));
            return;
        }

        // check ttf
        if (!isTtf(file.contents)) {
            cb(null, file);
            return;
        }

        // clone
        if (opts.clone) {
            this.push(file.clone(false));
        }
        
        
        file.path = replaceExt(file.path, '.base64');
        
        let output;
        try {
            output = file.contents = Buffer.from(  b2a(file.contents) );
        }catch(e){
            cb(e);
        }
        output && cb(null, file);
    });
};

let ttf2base64css = function(opts){
    opts = _.extend({clone: true}, opts);
        
    return through.ctor({
        objectMode: true
    }, function(file, enc, cb){
         // check null
        if (file.isNull()) {
            cb(null, file);
            return;
        }

        // check stream
        if (file.isStream()) {
            cb(new Error('Streaming is not supported'));
            return;
        }

        // check ttf
        if (!isTtf(file.contents)) {
            cb(null, file);
            return;
        }

        // clone
        if (opts.clone) {
            this.push(file.clone(false));
        }
        
        
        file.path = replaceExt(file.path, '.css');
        
        let output;
        try {
            output = file.contents = Buffer.from(  `@font-face {
    font-weight: normal;
    font-style: normal;
    font-family: "abc";
    src: url('data:font/opentype;base64,`+b2a(file.contents)+`\');
}` );
        }catch(e){
            cb(e);
        }
        output && cb(null, file);
    });
};

var fontmin = new Fontmin()
		.use(Fontmin.glyph({ 
        text: '0123456789.+-',
        //hinting: false         // keep ttf hint info (fpgm, prep, cvt). default = true
    }))
    //.use(Fontmin.ttf2svg())
    .use(ttf2base64())
    .use(ttf2base64css())
    .src('fonts/*.ttf')
    .dest('build/fonts');
    

fontmin.run(function (err, files) {
    if (err) {
        throw err;
    }
    console.log("构建成功" /*, files[0]*/);
});